<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="50%"
    :before-close="handleClose"
  >
    <el-form 
      :model="form" 
      ref="formRef"
      label-width="100px"
      :disabled="mode === 'detail'"
      :rules="rules"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option label="男性" :value="0"/>
              <el-option label="女性" :value="1"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option label="正常" :value="1"/>
              <el-option label="禁用" :value="0"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证件号" prop="idNumber">
            <el-input v-model="form.idNumber" placeholder="请输入证件号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input-number v-model="form.age" :min="0" :max="150"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入联系地址"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="form.remark" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">返回</el-button>
      <el-button 
        v-if="mode !== 'detail'" 
        type="primary" 
        @click="handleSubmit"
      >
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserDetail, addUser, updateUser } from '@/api/user'

const props = defineProps({
  modelValue: Boolean,
  mode: {
    type: String as () => 'add' | 'edit' | 'detail',
    default: 'add'
  },
  userId: Number
})

const emit = defineEmits(['update:modelValue', 'refresh'])

const visible = ref(false)
const form = ref({
  username: '',
  gender: '',
  age: 0,
  idNumber: '',
  phone: '',
  email: '',
  address: '',
  remark: '',
  status: 1
})

// 监听visible变化
watch(() => props.modelValue, (val) => {
  visible.value = val
})

// 监听visible变化同步给父组件
watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  idNumber: [
    { required: true, message: '请输入证件号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 0, max: 150, message: '年龄必须在0-150之间', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  form.value = {
    username: '',
    gender: 0,
    age: 0,
    idNumber: '',
    phone: '',
    email: '',
    address: '',
    remark: '',
    status: 1
  }
}

// 监听userId和mode变化加载用户详情
watch([() => props.userId, () => props.mode], async ([userId, mode]) => {
  if (userId && mode !== 'add') {
    try {
      console.log('加载用户详情:', userId, mode)
      const res = await getUserDetail(userId)
      console.log('用户详情数据:', res.data)
      
      // 根据后端返回的数据结构调整
      if (res.data && res.data.code === 200) {
        // 使用后端API返回的数据，将sexy字段转换为gender字段
        const userData = res.data.data
        form.value = {
          ...userData,
          gender: typeof userData.sexy !== 'undefined' ? Number(userData.sexy) : Number(userData.gender || 0),
          age: userData.age || 0
        }
        console.log('表单数据已更新:', form.value)
      } else if (res.data) {
        // 使用模拟数据
        const userData = res.data.data || res.data
        form.value = {
          ...userData,
          gender: typeof userData.sexy !== 'undefined' ? Number(userData.sexy) : Number(userData.gender || 0),
          age: userData.age || 0
        }
        console.log('表单数据已更新(模拟数据):', form.value)
      }
    } catch (error) {
      console.error('获取用户详情失败', error)
      ElMessage.error('获取用户详情失败，请稍后再试')
      resetForm()
    }
  } else {
    resetForm()
  }
}, { immediate: true })

// 弹窗标题
const dialogTitle = computed(() => {
  switch (props.mode) {
    case 'add': return '新增用户'
    case 'edit': return '编辑用户'
    case 'detail': return '用户详情'
    default: return ''
  }
})

// 关闭弹窗
const handleClose = () => {
  resetForm()
  visible.value = false
}

// 表单引用
const formRef = ref()

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (props.mode === 'add') {
      const res = await addUser(form.value)
      if (res.data && res.data.code === 200) {
        ElMessage.success('添加用户成功')
        emit('refresh')
        handleClose()
      }
    } else {
      const res = await updateUser({
        id: props.userId,
        ...form.value
      })
      if (res.data && res.data.code === 200) {
        ElMessage.success('更新用户成功')
        emit('refresh')
        handleClose()
      }
    }
  } catch (err) {
    console.error('保存用户信息失败', err)
    ElMessage.error('表单验证失败，请检查必填项')
  }
}
</script>
